package com.magupe.develop.reptile;

import com.magupe.develop.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ReptileService {

    public static List<Cookie> getCookieByLogin() {
        BasicCookieStore cookie = new BasicCookieStore();
        HttpClient httpClient = HttpUtils.sslClient(cookie);
        HttpPost httpPost = new HttpPost("https://login.taobao.com/newlogin/login.do?appName=taobao&fromSite=0");
        HttpResponse response = null;
        try {
            List<BasicNameValuePair> pairs = new ArrayList<>();
            pairs.add(new BasicNameValuePair("fm-login-id", "18738102014"));
            pairs.add(new BasicNameValuePair("fm-login-password", "ma.4102236058"));
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8);
            httpPost.setEntity(formEntity);

            // 设置请求头通用信息
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Connection", "keep-alive");
            httpPost.addHeader("Upgrade-Insecure-Requests", "1");
            httpPost.addHeader("Origin", "https://login.taobao.com");
            httpPost.addHeader("Referer", "https://login.taobao.com/member/login.jhtml?from=taobaoindex&f=top&style=&sub=true&redirect_url=https%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm");
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36");

            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                List<Cookie> cookies = cookie.getCookies();
                return cookies;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
